package com.ocm.commerceinteraction.ui;


import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ocm.commerceinteraction.GlobalApplication;
import com.ocm.commerceinteraction.MainActivity;
import com.ocm.commerceinteraction.R;
import com.ocm.commerceinteraction.config.RequestAddr;
import com.ocm.commerceinteraction.model.BaseModel;
import com.ocm.commerceinteraction.model.FriendsList;
import com.ocm.commerceinteraction.model.GroupMemberBean;
import com.ocm.commerceinteraction.model.UserModel;
import com.ocm.commerceinteraction.ui.adapter.XTContactAdapter;
import com.ocm.commerceinteraction.util.MethedUtil;
import com.ocm.commerceinteraction.util.XTHttp;
import com.ocm.commerceinteraction.util.helper.DBHelper;
import com.ocm.commerceinteraction.util.helper.LogHelper;
import com.ocm.commerceinteraction.util.helper.NotifyUtil;
import com.ocm.commerceinteraction.util.helper.StringHelper;
import com.ocm.commerceinteraction.util.http.AjaxCallBack;
import com.ocm.commerceinteraction.util.loading.Loading;
import com.ocm.commerceinteraction.util.view.sortlist.CharacterParser;
import com.ocm.commerceinteraction.util.view.sortlist.PinyinComparator;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import easeui.EaseConstant;
import easeui.controller.EaseUI;
import easeui.domain.EaseUser;
import easeui.ui.EaseContactListFragment;
import easeui.widget.EaseContactList;
import easeui.widget.EaseSidebar;
import easeui.widget.EaseTitleBar;

import static com.easemob.EMNotifierEvent.Event.EventNewMessage;
import static com.ocm.commerceinteraction.GlobalApplication.context;


@EFragment(R.layout.fragment_goodfriends)
public class GoodFriendsFragment extends BaseFragment  implements EMEventListener {


//    @ViewById(R.id.title_bar)
//    EaseTitleBar easeTitleBar;
    //    @ViewById(R.id.contact_list)
//    EaseContactList contactListLayout;

    @ViewById(R.id.iv_right_btn)
    ImageView iv_right_btn;
    @ViewById(R.id.toptitle_title)
    TextView topTitle;
    @ViewById(R.id.list)
    ListView listView;
    @ViewById(R.id.sidebar)
    EaseSidebar sidebar;

    @ViewById(R.id.right_text_btn)
    TextView right_text_btn;

    private CharacterParser characterParser;
    private List<GroupMemberBean> SourceDateList;
    private List<EaseUser> userlist = new ArrayList<>();
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;

    @Override
    @AfterViews
    void initView() {
        topTitle.setText("我的好友");
        right_text_btn.setVisibility(View.VISIBLE);
        if (GlobalApplication.newMsgFlag) {
            iv_right_btn.setImageDrawable(getResources().getDrawable(R.drawable.ic_message_new));
        } else {
            iv_right_btn.setImageDrawable(getResources().getDrawable(R.drawable.ic_message));
        }
        characterParser = CharacterParser.getInstance();
        loadData();
    }

    //加载数据
    String requestUrl = "";

    private void loadData() {
        requestUrl = RequestAddr.serarchFriList;
        GlobalApplication.xtHttp.get(requestUrl, new AjaxCallBack<Object>() {
            @Override
            public void onSuccess(Object o) {
                super.onSuccess(o);
                dealData(o);
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
            }
        });
    }

    //处理数据
    BaseModel baseModel;
    FriendsList friendsList;
    List<UserModel> userModelList = new ArrayList<>();
    XTContactAdapter xtContactAdapter;
    private void dealData(Object object) {
        try {
            friendsList = GlobalApplication.gson.fromJson(object.toString(), FriendsList.class);
        } catch (JsonSyntaxException e) {
            baseModel = GlobalApplication.gson.fromJson(object.toString(), BaseModel.class);
            Toast.makeText(getActivity(), baseModel.getMsg(), Toast.LENGTH_SHORT).show();
            return;
        }
        int flag = 0;
        boolean flagTag = false;
        userModelList.clear();
        String[] date = new String[friendsList.getData().size()];
        for (int i = 0; i < friendsList.getData().size(); i++) {
            date[i] = friendsList.getData().get(i).getNick();
        }
        SourceDateList = filledData(date);
        // 根据a-z进行排序源数据
        Collections.sort(SourceDateList, pinyinComparator);
        userlist.clear();
        for (int i = 0; i < SourceDateList.size(); i++) {
            for (int j = 0; j < friendsList.getData().size() ; j++) {
                if (friendsList.getData().get(j).getNick().equals(SourceDateList.get(i).getName())) {
                    EaseUser easeUser = new EaseUser(friendsList.getData().get(j).getNick());
                    easeUser.setInitialLetter(SourceDateList.get(i).getSortLetters());
                    easeUser.setSelect(false);
                    easeUser.setEid(friendsList.getData().get(j).getUser_uniq_id());
                    easeUser.setAvatar(friendsList.getData().get(j).getIcon());
                    easeUser.setUsername(friendsList.getData().get(j).getNick());
                    userlist.add(easeUser);
                    break;
                }
            }
        }
        xtContactAdapter = new XTContactAdapter(getActivity(),0,userlist, 0);
        listView.setAdapter(xtContactAdapter);

//        DBHelper.removeMoveFriendList();
        DBHelper.addFriendList(friendsList);
        GlobalApplication.userInfoList = DBHelper.getFriendlist();
        //get easeui instance
        GlobalApplication.easeUI = EaseUI.getInstance();
////需要easeui库显示用户头像和昵称设置此provider
        GlobalApplication.easeUI.setUserProfileProvider(new EaseUI.EaseUserProfileProvider() {

            @Override
            public EaseUser getUser(String username) {
                return getUserInfo(username);
            }
        });

    }

    @ItemClick(R.id.list)
    void userOnItemClick(int position) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
        bundle.putString(EaseConstant.EXTRA_USER_ID, userlist.get(position).getEid());
        bundle.putString("name", userlist.get(position).getNick());
        GlobalApplication.unReadListFri.remove(userlist.get(position).getEid());
        xtContactAdapter.notifyDataSetChanged();
        intent.setClass(getActivity(), ChatActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    private List<GroupMemberBean> filledData(String[] date) {
        List<GroupMemberBean> mSortList = new ArrayList<GroupMemberBean>();

        for (int i = 0; i < date.length; i++) {
            GroupMemberBean sortModel = new GroupMemberBean();
            sortModel.setName(date[i]);
            // 汉字转换成拼音
            String pinyin = characterParser.getSelling(date[i]);
            if (pinyin.equals("")){
                pinyin = "#";
            }
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }

    @Override
    public void onResume() {
        super.onResume();
//        initView();
        EaseUI.getInstance().pushActivity(getActivity());
        // register the event listener when enter the foreground
        EMChatManager.getInstance().registerEventListener(
                this,
                new EMNotifierEvent.Event[]{EventNewMessage});
    }


    @Click({R.id.right_layout, R.id.left_layout, R.id.back_btn})
    void Click(View view) {
        switch (view.getId()) {
            case R.id.right_layout:
                MainActivity.switchFragment(this, new SearchUserFragment_());
                break;
            case R.id.back_btn:
                GlobalApplication.newMsgFlag = false;
                MainActivity.switchFragment(this, new MeaageFragment_());
                break;
        }
    }

    private EaseUser getUserInfo(String username) {
        //获取user信息，demo是从内存的好友列表里获取，
        //实际开发中，可能还需要从服务器获取用户信息,
        //从服务器获取的数据，最好缓存起来，避免频繁的网络请求
        EaseUser easeUser = null;
        if (username.equals(GlobalApplication.loginModel.getData().getUser_uniq_id())) {
            easeUser = new EaseUser(username);
            easeUser.setAvatar(RequestAddr.baseUrl + GlobalApplication.loginModel.getData().getIcon());
            easeUser.setUsername(GlobalApplication.loginModel.getData().getUser_uniq_id());
            easeUser.setSelect(false);
            easeUser.setEid(GlobalApplication.loginModel.getData().getUser_uniq_id());
            easeUser.setNick(GlobalApplication.loginModel.getData().getNick());
            return easeUser;
        }
        for (int i = 0; i < GlobalApplication.userInfoList.size(); i++) {
            if (username.equals(GlobalApplication.userInfoList.get(i).getUser_uniq_id())) {
                easeUser = new EaseUser(GlobalApplication.userInfoList.get(i).getUser_uniq_id());
                easeUser.setAvatar(RequestAddr.baseUrl + GlobalApplication.userInfoList.get(i).getIcon());
                easeUser.setUsername(GlobalApplication.userInfoList.get(i).getUser_uniq_id());
                easeUser.setSelect(false);
                easeUser.setEid(GlobalApplication.userInfoList.get(i).getUser_uniq_id());
                easeUser.setNick(GlobalApplication.userInfoList.get(i).getNick());
            }
        }
        return easeUser;
    }

    NotifyUtil notifyUtil;
    @Override
    public void onEvent(EMNotifierEvent event) {
        switch (event.getEvent()) {
            case EventNewMessage:
                // 获取到message
                EMMessage message = (EMMessage) event.getData();
                String username = null;
                // 群组消息
                if (message.getChatType() == EMMessage.ChatType.GroupChat || message.getChatType() == EMMessage.ChatType.ChatRoom) {
                    username = message.getTo();
                } else {
                    // 单聊消息
                    username = message.getFrom();
                }
                // 如果是当前会话的消息，刷新聊天页面
                LogHelper.i("user*********:" + message.getFrom());

                notifyUtil = new NotifyUtil(context, 1);
                Random random = new Random(System.currentTimeMillis());
                PendingIntent contentIntent = PendingIntent.getActivity(context,
                        random.nextInt(), new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
                String Title1 = "";
                if (message.getChatType() == EMMessage.ChatType.GroupChat) {
                    for (int i = 0; i < GlobalApplication.userGroupDetail.getData().size(); i++) {
                        if (GlobalApplication.userGroupDetail.getData().get(i).getHuanxing_groupid().equals(message.getTo())){
                            Title1 = GlobalApplication.userGroupDetail.getData().get(i).getGroupname();
                        }
                    }
                } else {
                    for (int i = 0; i < GlobalApplication.userInfoList.size(); i++) {
                        if (GlobalApplication.userInfoList.get(i).getUser_uniq_id().equals(message.getFrom())) {
                            Title1 = GlobalApplication.userInfoList.get(i).getNick();
                        }
                    }
//                    xtContactAdapter.notifyDataSetChanged();
                }
                notifyUtil.notify_normal_singline(contentIntent, R.mipmap.logo, "", Title1, "发来新消息", true, true, true);
                if (message.getChatType() == EMMessage.ChatType.GroupChat) {
                    username = message.getTo();
                    if (GlobalApplication.unReadListGroup.get(message.getTo()) != null) {
                        int numGroup = GlobalApplication.unReadListGroup.get(message.getTo());
                        GlobalApplication.unReadListGroup.put(message.getTo(), ++numGroup);
                    } else {
                        GlobalApplication.unReadListGroup.put(message.getTo(), 1);
                    }
                } else if (message.getChatType() == EMMessage.ChatType.Chat) {
                    if (GlobalApplication.unReadListFri.get(message.getFrom()) != null) {
                        int numFri = GlobalApplication.unReadListFri.get(message.getFrom());
                        GlobalApplication.unReadListFri.put(message.getFrom(), ++numFri);
                    } else {
                        GlobalApplication.unReadListFri.put(message.getFrom(), 1);
                    }
                }
//                }

                break;
            default:
                break;
        }
    }

    @Override
    public void onPause() {
        super.onStop();
        EMChatManager.getInstance().unregisterEventListener(this);
    }
}
